const wechatService = require('../services/wechatService');
const { AppError } = require('../middlewares/errorHandler');
const { SystemLog, User, Order, Payment } = require('../models');
const { generateToken } = require('../utils/auth');
const { wechatPay } = require('../services/payment.service');

class WechatController {
  // 创建小程序
  async createApp(ctx) {
    const appData = ctx.request.body;
    const app = await wechatService.createApp(appData);

    // 记录操作日志
    await SystemLog.create({
      action: 'create_wechat_app',
      operator: ctx.state.user.id,
      target_type: 'wechat_app',
      target_id: app.id,
      details: { app }
    });

    ctx.status = 201;
    ctx.body = {
      status: 'success',
      data: app
    };
  }

  // 获取所有小程序
  async getAllApps(ctx) {
    const apps = await wechatService.getAllApps();
    ctx.body = {
      status: 'success',
      data: apps
    };
  }

  // 获取单个小程序
  async getApp(ctx) {
    const { id } = ctx.params;
    const app = await wechatService.getApp(id);
    
    if (!app) {
      throw new AppError(404, '小程序不存在');
    }

    ctx.body = {
      status: 'success',
      data: app
    };
  }

  // 更新小程序
  async updateApp(ctx) {
    const { id } = ctx.params;
    const updateData = ctx.request.body;

    const app = await wechatService.getApp(id);
    if (!app) {
      throw new AppError(404, '小程序不存在');
    }

    const updatedApp = await wechatService.updateApp(id, updateData);

    // 记录操作日志
    await SystemLog.create({
      action: 'update_wechat_app',
      operator: ctx.state.user.id,
      target_type: 'wechat_app',
      target_id: id,
      details: { before: app, after: updatedApp }
    });

    ctx.body = {
      status: 'success',
      data: updatedApp
    };
  }

  // 删除小程序
  async deleteApp(ctx) {
    const { id } = ctx.params;

    const app = await wechatService.getApp(id);
    if (!app) {
      throw new AppError(404, '小程序不存在');
    }

    await wechatService.deleteApp(id);

    // 记录操作日志
    await SystemLog.create({
      action: 'delete_wechat_app',
      operator: ctx.state.user.id,
      target_type: 'wechat_app',
      target_id: id,
      details: { app }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 处理支付回调
  async handlePaymentNotify(ctx) {
    const { appId } = ctx.params;
    const notifyData = ctx.request.body;

    try {
      // 验证通知数据
      const verifyResult = await wechatPay.verifyNotify(ctx.headers, ctx.request.rawBody);
      
      if (!verifyResult) {
        throw new AppError(400, '回调数据验证失败');
      }

      // 查询支付记录
      const payment = await Payment.findOne({
        where: { 
          order_number: notifyData.out_trade_no,
          method: 'wechat'
        },
        include: [{
          model: Order,
          as: 'order'
        }]
      });

      if (!payment) {
        throw new AppError(404, '支付记录不存在');
      }

      // 更新支付状态
      if (notifyData.trade_state === 'SUCCESS' && payment.status !== 'completed') {
        await payment.update({
          status: 'completed',
          paid_at: new Date(),
          transaction_id: notifyData.transaction_id,
          response: notifyData
        });

        // 更新订单状态
        await payment.order.update({ status: 'paid' });

        // 记录日志
        await SystemLog.create({
          action: 'payment_completed',
          target_type: 'payment',
          target_id: payment.id,
          details: { 
            orderNo: notifyData.out_trade_no,
            transactionId: notifyData.transaction_id
          }
        });
      }

      // 返回成功响应
      ctx.body = {
        code: 'SUCCESS',
        message: 'OK'
      };
    } catch (error) {
      // 记录错误日志
      await SystemLog.create({
        action: 'payment_notify_failed',
        target_type: 'payment',
        details: { 
          error: error.message,
          notifyData
        }
      });

      throw new AppError(400, '处理支付回调失败：' + error.message);
    }
  }

  // 生成小程序码
  async generateQRCode(ctx) {
    const { appId, path, width = 430 } = ctx.request.body;
    const qrCode = await wechatService.generateQRCode(appId, path, { width });
    
    ctx.type = 'image/png';
    ctx.body = qrCode;
  }

  // 发送订阅消息
  async sendTemplateMessage(ctx) {
    const { appId, touser, templateId, data, page } = ctx.request.body;
    const result = await wechatService.sendTemplateMessage(appId, touser, templateId, data, page);
    
    ctx.body = {
      status: 'success',
      data: result
    };
  }

  // 微信登录
  async login(ctx) {
    const { code, appId } = ctx.request.body;

    if (!code || !appId) {
      throw new AppError(400, '缺少必要参数');
    }

    try {
      // 通过code获取微信用户信息
      const sessionInfo = await wechatService.code2Session(appId, code);
      
      // 查找或创建用户
      let user = await User.findOne({
        where: { wechat_open_id: sessionInfo.openid }
      });

      if (!user) {
        // 创建新用户
        user = await User.create({
          wechat_open_id: sessionInfo.openid,
          wechat_union_id: sessionInfo.unionid,
          status: 'active',
          roles: ['user']
        });

        // 记录日志
        await SystemLog.create({
          action: 'user_created',
          target_type: 'user',
          target_id: user.id,
          details: { 
            method: 'wechat_login',
            openid: sessionInfo.openid
          }
        });
      }

      // 生成JWT令牌
      const token = generateToken(user);

      // 更新用户最后登录时间
      await user.update({ 
        last_login_at: new Date(),
        wechat_session_key: sessionInfo.sessionKey
      });

      ctx.body = {
        status: 'success',
        data: {
          token,
          user: {
            id: user.id,
            openid: user.wechat_open_id,
            unionid: user.wechat_union_id,
            roles: user.roles
          }
        }
      };
    } catch (error) {
      // 记录错误日志
      await SystemLog.create({
        action: 'login_failed',
        target_type: 'wechat_login',
        details: { 
          error: error.message,
          code,
          appId
        }
      });

      throw new AppError(400, '微信登录失败：' + error.message);
    }
  }

  // 创建支付订单
  async createPayment(ctx) {
    const { appId, orderNo, totalFee, description, paymentType, openid } = ctx.request.body;

    // 参数验证
    if (!appId || !orderNo || !totalFee || !description || !paymentType) {
      throw new AppError(400, '缺少必要参数');
    }

    if (paymentType === 'JSAPI' && !openid) {
      throw new AppError(400, 'JSAPI支付需要提供openid');
    }

    try {
      // 查询订单
      const order = await Order.findOne({
        where: { order_number: orderNo }
      });

      if (!order) {
        throw new AppError(404, '订单不存在');
      }

      if (order.status !== 'pending') {
        throw new AppError(400, '订单状态不允许支付');
      }

      // 创建支付记录
      const payment = await Payment.create({
        order_id: order.id,
        amount: totalFee,
        method: 'wechat',
        status: 'pending',
        app_id: appId,
        payment_type: paymentType
      });

      // 调用微信支付接口
      let payResult;
      if (paymentType === 'JSAPI') {
        payResult = await wechatPay.createMiniProgramOrder({
          outTradeNo: orderNo,
          totalFee,
          body: description,
          openid
        });
      } else if (paymentType === 'H5') {
        payResult = await wechatPay.createH5Order({
          outTradeNo: orderNo,
          totalFee,
          body: description,
          ip: ctx.ip
        });
      }

      // 更新支付记录
      await payment.update({
        prepay_id: payResult.prepay_id,
        response: payResult
      });

      ctx.body = {
        status: 'success',
        data: {
          prepayId: payResult.prepay_id,
          payParams: payResult.payment_params
        }
      };

      // 记录日志
      await SystemLog.create({
        action: 'payment_created',
        target_type: 'payment',
        target_id: payment.id,
        operator: ctx.state.user.id,
        details: { 
          orderNo,
          paymentType,
          amount: totalFee
        }
      });
    } catch (error) {
      // 记录错误日志
      await SystemLog.create({
        action: 'payment_creation_failed',
        target_type: 'payment',
        operator: ctx.state.user.id,
        details: { 
          error: error.message,
          orderNo,
          paymentType
        }
      });

      throw new AppError(400, '创建支付订单失败：' + error.message);
    }
  }

  // 查询支付订单
  async queryPayment(ctx) {
    const { orderNo } = ctx.params;

    try {
      // 查询支付记录
      const payment = await Payment.findOne({
        where: { 
          order_number: orderNo,
          method: 'wechat'
        },
        include: [{
          model: Order,
          as: 'order'
        }]
      });

      if (!payment) {
        throw new AppError(404, '支付记录不存在');
      }

      // 调用微信支付查询接口
      const queryResult = await wechatPay.queryOrderStatus(orderNo);

      // 更新支付状态
      if (queryResult.trade_state === 'SUCCESS' && payment.status !== 'completed') {
        await payment.update({
          status: 'completed',
          paid_at: new Date(),
          transaction_id: queryResult.transaction_id,
          response: queryResult
        });

        // 更新订单状态
        await payment.order.update({ status: 'paid' });
      }

      ctx.body = {
        status: 'success',
        data: {
          tradeState: queryResult.trade_state,
          tradeStateDesc: queryResult.trade_state_desc,
          transactionId: queryResult.transaction_id
        }
      };
    } catch (error) {
      throw new AppError(400, '查询支付订单失败：' + error.message);
    }
  }

  // 申请退款
  async refundPayment(ctx) {
    const { orderNo, refundNo, totalFee, refundFee, reason } = ctx.request.body;

    try {
      // 查询支付记录
      const payment = await Payment.findOne({
        where: { 
          order_number: orderNo,
          method: 'wechat',
          status: 'completed'
        }
      });

      if (!payment) {
        throw new AppError(404, '支付记录不存在或未支付完成');
      }

      // 创建退款记录
      const refund = await payment.createRefund({
        refund_no: refundNo,
        amount: refundFee,
        reason,
        status: 'pending'
      });

      // 调用微信退款接口
      const refundResult = await wechatPay.refundOrder({
        outTradeNo: orderNo,
        outRefundNo: refundNo,
        totalFee,
        refundFee,
        reason
      });

      // 更新退款记录
      await refund.update({
        status: 'processing',
        refund_id: refundResult.refund_id,
        response: refundResult
      });

      ctx.body = {
        status: 'success',
        data: {
          refundId: refundResult.refund_id
        }
      };

      // 记录日志
      await SystemLog.create({
        action: 'refund_created',
        target_type: 'refund',
        target_id: refund.id,
        operator: ctx.state.user.id,
        details: { 
          orderNo,
          refundNo,
          amount: refundFee
        }
      });
    } catch (error) {
      // 记录错误日志
      await SystemLog.create({
        action: 'refund_failed',
        target_type: 'refund',
        operator: ctx.state.user.id,
        details: { 
          error: error.message,
          orderNo,
          refundNo
        }
      });

      throw new AppError(400, '申请退款失败：' + error.message);
    }
  }
}

module.exports = new WechatController(); 